﻿using UnityEngine;
using System.Collections;

public class CameraScript : MonoBehaviour {

	public playerGui playGUI;

    public GameObject PlayerFab;
	public float speed = 10.0f;

	Character [] players;
    [HideInInspector] public Transform Trnsfrm;
    Camera Cam;
    void Awake() {
        Cam = camera;
         Trnsfrm = transform;
    }
    public GameObject [] P;
	void Start () {
       players = FindObjectsOfType<Character>();
        /*
        var p = GameObject.FindGameObjectsWithTag( "Player" );
        P =p;
        players = new Character[p.Length]; int i = 0;
        foreach(GameObject go in p) { 
            players[i++] = go.GetComponent<Character>();
            Debug.Log("adhj "+go.name);
        }
	        */
	}
	float SmoothSpd = 0;
	// Update is called once per frame
	void Update () {

        //float minx = float.MaxValue;
        float avgx = 0, cnt = 0;
        var spd = speed ;
		foreach( Character c in players ) {
			
			var sp = Cam.WorldToViewportPoint( c.Trnsfrm.position );
            //minx = Mathf.Min(minx, sp.x );
            if(sp.x < 0.0f) {
                if(c.ForceTimer < Time.time) {
                    c.shove( new Vector3(1000.0f,Random.Range(-100,100.0f),0), Trnsfrm.position );
                }               
                c.DieMuthaFucka();                    
                
            } else if( !c.Dead ) { 
                avgx += sp.x;

                cnt++;
            }
		}
        if(cnt > 0 && (avgx /= cnt) >0.3f) {
            spd += Mathf.Pow( (avgx -0.3f)*3.0f, 2.0f)*10.0f;          
        }
        SmoothSpd = Mathf.Lerp( SmoothSpd,spd,3.0f*Time.deltaTime);

		transform.position += new Vector3 (SmoothSpd*Time.deltaTime, 0, 0);
	
	}

    public void respawn(int i) {
		playGUI.deaths [i]++;
        var go = (GameObject)Instantiate( PlayerFab);
        var c = go.GetComponent<Character>();
        c.set(i);

        Vector3 p = Trnsfrm.position;
        for(int j = players.Length; j-- > 0;) {
            if(players[j].PlayerInd ==i) {
                players[j] = c;
                i = -2;
            } else {
                p.x = (p.x+players[j].Trnsfrm.position.x)*0.5f;
            }
        }
        p.z = p.y = 0;
        p += c.Trnsfrm.up *4.0f;

        c.Trnsfrm.position = p;

     
    }
}
